﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RG.Common.Configuration;
using RG.Common.WPF.Commands;
using Microsoft.Practices.Unity;

namespace RG.Common.WPF.Filters.ToolBarFilters
{
    [SupportDataBinding]
    public class FilterComboBoxFrameVM : FilterBaseParamVM<List<int>>
    {

        public FilterComboBoxFrameVM(IUnityContainer cfg):base(cfg)
        {
            Items = new ObservableCollection<string>();
        }

        private string selectedItem;

        [PropertySetting(SaveNullValue = true)]
        public string SelectedItem
        {
            get { return selectedItem; }
            set
            {
                selectedItem = value;
                var key = ItemDictionary != null ? ItemDictionary.SafeGetKey(value, -100) : -100;
                Value = key == -100 ? new List<int>() : new List<int> { key };
                if (OnStateChanged != null)
                    OnStateChanged.Execute(this);
            }
        }

        private Dictionary<int, string> itemDictionary;
        public Dictionary<int, string> ItemDictionary
        {
            get { return itemDictionary; }
            set
            {
                itemDictionary = value;
                Items = new ObservableCollection<string>(ItemDictionary.Values);
            }
        }

        public ObservableCollection<string> Items { get; set; }

        public override void ClearValueQuiet()
        {
            SelectedItem = null;
        }


        public string FormattedValue
        {
            get
            {
                if (string.IsNullOrEmpty(SelectedItem)) return EmptyText;
                return SelectedItem;
            }
        }

        public int? SelectedValue()
        {
            var sel = ItemDictionary.Where(x => x.Value == SelectedItem).Select(y => y.Key);
            return sel.Count() > 0 ? (int?) sel.FirstOrDefault() : null;
        }

        public override bool ValueEmpty()
        {
            return value==null || !value.Any();
        }

        public List<int> SelectedIds
        {
            get
            {
                var id = SelectedValue();
                return id.HasValue ? new List<int> {id.Value} : null;
            }
        }

        public DelegateCommand<FilterBaseVM> OnStateChanged { get; set; }
        protected override List<int> ReturnDefaultEmptyValue()
        {
            return null;
        }
    }
}
